// import { generateDynamicRoutes } from '@/router/helper';
import { resetRouter } from '@/router';
// import { generateDynamicRoutes } from '@/router/helper';
import { DefaultService as Api } from '@/servers';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import type { RouteRecordRaw } from 'vue-router';

export const useUserStore = defineStore(
  'user',
  () => {
    // 锁屏；重置token
    // const lockScreenStore = useLockScreenStore()

    const token = ref<string>('');
    const perms = ref<string[]>([]);
    const menus = ref<RouteRecordRaw[]>([]);
    const userInfo = ref<Partial<API.UserEntity>>({});
    // const options = ref<PackageType[]>([]);
    const regions = ref<Region[]>([]);

    const sortMenus = (menus: RouteRecordRaw[]) => {
      return menus
        .filter(n => {
          // 过滤掉需要隐藏的菜单
          return !n.meta?.hidden;
        })
        .sort((a, b) => ~~Number(a.meta?.order) - ~~Number(b.meta?.order));
    };

    const generateMenus = (menu: API.MenuItem[]) => {
      const result = [] as RouteRecordRaw[];
      const getRoute = ({ children, ...rest }: API.MenuItem) => {
        rest.path = rest.path.toLowerCase();
        return {
          path: rest.path,
          name: rest.path,
          component: () => {},
          children: children && children?.length ? generateMenus(children) : [],
          meta: { ...rest }
        };
      };
      menu.forEach(item => result.push(getRoute(item)));
      return result;
    };

    const generatePerms = (menu: API.MenuItem[]) => {
      const result = new Map();

      menu.forEach(item => {
        item.children?.forEach(child => {
          if (child.children) {
            for (const grandchild of child.children) {
              result.set(String(item.path).toLowerCase() + '/' + String(child.path).toLowerCase(), grandchild.model);
            }
          }
        });
      });

      return result;
    };

    /** 清空用户登录态(token, userInfo...) */
    const clearLoginState = () => {
      token.value = '';
      perms.value = [];
      menus.value = [];
      userInfo.value = {};
      // resetRouter();
      setTimeout(() => {
        localStorage.clear();
      });
    };

    /** 登录成功保存token */
    const setToken = (_token: string) => {
      token.value = _token;
    };

    /** 登录 */
    const login = async (params: API.LoginDto) => {
      try {
        const { data } = (await Api.postUserLogin(params)) as unknown as API.MacResult;

        setToken(data.token);
        await afterLogin(data);
        // lockScreenStore.setLock(false);
        // lockScreenStore.saveLoginPwd(params.password);
      } catch (error) {
        return Promise.reject(error);
      }
    };

    /** 登录成功之后, 获取用户信息以及生成权限路由 */
    const afterLogin = async (__login_info: {
      user_info: API.UserEntity;
      // dict_data: PackageType[];
      dict_world: Region[];
    }) => {
      try {
        userInfo.value = __login_info.user_info;
        // options.value = __login_info.dict_data;
        regions.value = __login_info.dict_world;

        await fetchPermsAndMenus();
      } catch (error) {
        return Promise.reject(error);
        // return logout();
      }
    };

    /** 获取用户权限和菜单 */
    const fetchPermsAndMenus = async function () {
      const { getPublicMenu } = Api;
      const [{ data: _menus }, _roles] = await Promise.all([getPublicMenu(), () => void 0]);

      // console.log(_menus, _roles);

      sortMenus([]); // 无需排序

      // generateDynamicRoutes(_menus as API.MenuItem[]);
      menus.value = generateMenus(_menus as API.MenuItem[]);
      perms.value = generatePerms(_menus as API.MenuItem[]);
    };

    /** 登出 */
    const logout = async () => {
      clearLoginState();
    };

    return {
      token,
      perms,
      menus,
      userInfo,
      // options,
      regions,
      login,
      logout,
      fetchPermsAndMenus,
      clearLoginState
    };
  },
  {
    persist: true
  }
);

// type PackageType = {
//   name: string;
//   data: Record<string, string>; // 以字符串为键，字符串为值的对象
//   endata: Record<string, string>; // 以字符串为键，字符串为值的对象
// };

type Region = {
  id: number;
  name: string;
  country_code: string;
  currency_code: string;
  cname: string; // 中文名
  oCountry: number; // 其它相关标识或计数
  pCountry: number; // 其它相关标识或计数
  sCountry: number; // 其它相关标识或计数
  mCountry: number; // 其它相关标识或计数
};
